import 'dart:async';
import 'dart:convert';

import 'package:appsflyer_sdk/appsflyer_sdk.dart';
// import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';

import 'JKlocalStorage.dart';
// import '../tools/JKlocalStorage.dart';

class NyL_AppflyerTool {
  // // 单例模式
  // 私有构造函数防止直接实例化
  NyL_AppflyerTool._();
  // 定义一个静态私有成员变量来存储唯一实例
  static final NyL_AppflyerTool _instance = NyL_AppflyerTool._();
  // 定义一个公开的静态方法来获取唯一实例
  static NyL_AppflyerTool get instance => _instance;

  static const String _afDevKey = 'fUQubGg5agnDgCJoweqs7a';
  // static const String _appId = 'com.sqr.playscore';
  static const String _appId = '6740313523'; //ios

  late String? af_deep_link = '';
  late String? af_firstTime_deeplink = '';
  late String? af_onInstallData = '';
  late String? af_DLStatus = '';

  late bool _islaunched;

  late StreamController<String> deepLinkStreamController =
      StreamController<String>.broadcast();

  //afDevKey在appsflyer后台，创建好应用可见，appid从应用商店复制
  static final AppsFlyerOptions _options = AppsFlyerOptions(
    afDevKey: _afDevKey,
    appId: _appId,
    timeToWaitForATTUserAuthorization: 5,
    showDebug: false, //调试模式 - 设置为true仅用于测试，请勿将此参数设置为发布到生产环境!true
  );

  late AppsflyerSdk appsflyerSdk = AppsflyerSdk(_options);

  //初始化sdk
  _configSDK() {
    appsflyerSdk.initSdk(
        registerConversionDataCallback: true,
        registerOnAppOpenAttributionCallback: true,
        registerOnDeepLinkingCallback: true);

    // appsflyerSdk.startSDK();
    // debugPrint("---------startSDK");
  }

  configDeepLink() async {
    af_firstTime_deeplink =
        await JKLocalStorage.getString('af_firstTime_deeplink');
    af_onInstallData =
        await JKLocalStorage.getString('onInstallConversionData');
    af_DLStatus = await JKLocalStorage.getString('af_DLStatus');

    _islaunched = await JKLocalStorage.getBool("_islaunched") ?? false;

    appsflyerSdk.onInstallConversionData((res) {
      debugPrint("onInstallConversionData res: " + res.toString());
      Map<String, dynamic> data = res['payload'];

      if (af_onInstallData!.isEmpty) {
        debugPrint("---------save onInstallConversionData");
        af_onInstallData = json.encode(data);
        JKLocalStorage.setString('onInstallConversionData', af_onInstallData!);
      }
      if (af_DLStatus! == 'NOT_FOUND') {
        debugPrint("---------Organic LAUNCH");
        deepLinkStreamController.add('Organic LAUNCH');
      }
      // deepLinkStreamController.add('SECOND_LAUNCH');
      if (af_firstTime_deeplink!.isNotEmpty && af_onInstallData!.isNotEmpty) {
        debugPrint("---------LINK LAUNCH");
        deepLinkStreamController.add('LINK LAUNCH');
      } else {
        debugPrint("---------NOT LINK");
        deepLinkStreamController.add('NOT LINK');
      }

      if (!_islaunched) {
        _islaunched = true;
        JKLocalStorage.setBool("_islaunched", true);
        debugPrint("JKLocalStorage.setBool(" 'is_first_launch' ", true);");
      }
    });

    //统一深度链接
    appsflyerSdk.onDeepLinking((DeepLinkResult dp) {
      switch (dp.status) {
        case Status.FOUND:
          debugPrint("deep link value: ${dp.deepLink?.deepLinkValue}");
          var dpString = jsonEncode(dp.deepLink!.clickEvent);
          if (dpString.isNotEmpty) {
            af_deep_link = dpString;
          }
          if (af_firstTime_deeplink!.isEmpty && dpString.isNotEmpty) {
            af_firstTime_deeplink = dpString;
            JKLocalStorage.setString('af_firstTime_deeplink', dpString);
            debugPrint("save-af_firstTime_deeplink");
          }

          debugPrint("dpString--$dpString");
          if (af_firstTime_deeplink!.isNotEmpty &&
              af_onInstallData!.isNotEmpty) {
            af_DLStatus = 'LINK FOUND';
            JKLocalStorage.setString('af_DLStatus', af_DLStatus!);
            deepLinkStreamController.add(dpString);
          }

          break;
        case Status.NOT_FOUND:
          debugPrint("deep link not found");
          af_firstTime_deeplink = '';
          af_deep_link = '';
          af_DLStatus = 'NOT_FOUND';
          JKLocalStorage.setString('af_DLStatus', af_DLStatus!);
          deepLinkStreamController.add('NOT_FOUND');
          break;
        case Status.ERROR:
          debugPrint("deep link error: ${dp.error}");
          deepLinkStreamController.add("LINK ERROR");
          break;
        case Status.PARSE_ERROR:
          debugPrint("deep link status parsing error");
          deepLinkStreamController.add("LINK PARSE_ERROR");
          break;
      }

      debugPrint("onDeepLinking res: " + dp.toString());
    });

    // App open attribution callback
    // appsflyerSdk.onAppOpenAttribution((res) {
    //   print("onAppOpenAttribution res: " + res.toString());
    //   // setState(() {
    //   //   _deepLinkData = res;
    //   // });
    // });
    _configSDK();
  }
}
